package com.innovation.chengzhangriji.ui.widget;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.BabyResponse;

public class JoinAdapter extends RecyclerView.Adapter<JoinViewHolder> implements JoinViewHolder.OnClickJoinListener {

    private BabyResponse[] mBabyResponses;

    private boolean[] mSelects;

    private int mSelect;

    @Override
    public JoinViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_join, parent, false);
        JoinViewHolder viewHolder = new JoinViewHolder(view);
        viewHolder.setOnClickJoinListener(this);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(JoinViewHolder holder, int position) {
        holder.setText(mBabyResponses[position].getName());
        holder.setHead(mBabyResponses[position].getImageUrl(), mBabyResponses[position].getGender());
        holder.setSelectVisibility(mSelects[position]);
    }

    @Override
    public int getItemCount() {
        if (mBabyResponses == null || mBabyResponses.length == 0) {
            return 0;
        }
        return mBabyResponses.length;
    }

    public void setBabyResponses(BabyResponse[] responses) {
        mBabyResponses = responses;
        mSelects = new boolean[responses.length];
        mSelects[0] = true;
    }

    @Override
    public void onClickJoin(JoinViewHolder holder) {
        for (int i = 0; i < mSelects.length; i++) {
            if (mSelects[i]) {
                mSelects[i] = false;
                notifyItemChanged(i);
                break;
            }
        }
        mSelect = holder.getLayoutPosition();
        mSelects[mSelect] = true;
        notifyItemChanged(mSelect);
    }

    public int getJoinBabyID() {
        if (mBabyResponses == null || mBabyResponses.length == 0) {
            return -1;
        }
        return mBabyResponses[mSelect].getId();
    }
}
